﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace HabitAnalyzer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        DbUtility db;
        ObservableCollection<string> _CatNames = new ObservableCollection<string>();

        int sessionID;
        DateTime sessionStartDate;
        DateTime sessionEndDate;

        public MainWindow()
        {
            InitializeComponent();
            db = new DbUtility();

            if (db.DatabaseExists() == false)
            {
                db.CreateDatabase();
            }

            //Load Data into windows
            LoadCategoriesList();
            LoadCategoriesCombo();
            LoadActivtiesList();
            LoadSessionList();

        }

        private void LoadSessionList()
        {
            var ses = db.GetSessionsForListBox();
            listBoxSessions.SelectedValuePath = "SessionID";
            listBoxSessions.DisplayMemberPath = "SessionName";
            listBoxSessions.ItemsSource = ses;
        }

        private void LoadActivtiesList()
        {
            var acts = db.GetActivities();
            listboxActivities.SelectedValuePath = "ActivityID";
            listboxActivities.DisplayMemberPath = "Name";
            listboxActivities.ItemsSource = acts;
        }

        private void LoadCategoriesList()
        {
            var cats = db.GetCategories();
            listOfCategories.SelectedValuePath = "CategoryID";
            listOfCategories.DisplayMemberPath = "Name";
            listOfCategories.ItemsSource = cats;
        }

        private void LoadCategoriesCombo()
        {
            var cats = db.GetCategories();
            comboboxNewActivityCategory.SelectedValuePath = "CategoryID";
            comboboxNewActivityCategory.DisplayMemberPath = "Name";
            comboboxNewActivityCategory.ItemsSource = cats;

            //populates categories combo box on record page - Kyle
            comboBox7.SelectedValuePath = "CategoryID";
            comboBox7.DisplayMemberPath = "Name";
            comboBox7.ItemsSource = cats;
        }

        //Function to populate the activities combobox in record page - Kyle
        private void LoadActivitiesCombo()
        {
            var acts = db.GetActivitiesByCategory((int)comboBox7.SelectedValue);
            comboBox9.SelectedValuePath = "ActivityID";
            comboBox9.DisplayMemberPath = "Name";
            comboBox9.ItemsSource = acts;

        }

        // Categories Tab
        private void textboxNewCategoryName_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void buttonCreateCategory_Click(object sender, RoutedEventArgs e)
        {
            if ((string)textboxCategoryName.Text.Trim() == "")
            {
                System.Windows.Forms.MessageBox.Show("Please enter a name for the category");
            }
            else
            {
                bool alreadyExists = false;

                foreach (Category item in listOfCategories.Items)
                {
                    if (item.Name == textboxCategoryName.Text)
                        alreadyExists = true;
                }

                if (alreadyExists == false)
                {
                    db.InsertCategory(textboxCategoryName.Text);
                    LoadCategoriesList();
                    LoadCategoriesCombo();
                    MessageBox.Show("Category Added.");
                }
                else
                {
                    MessageBox.Show("Category already exists!");
                }
            }

        }

        // Activities Tab
        private void comboNewActivityCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void buttonRecordNewActivity(object sender, RoutedEventArgs e)
        {
            if (comboboxNewActivityCategory.SelectedValue == null)
            {
                System.Windows.Forms.MessageBox.Show("Please select a category");
            }
            else
            {
                bool alreadyExists = false;

                foreach (Acitivity item in listboxActivities.Items)
                {
                    if (item.Name == textboxNewActivityName.Text)
                        alreadyExists = true;
                }

                if (alreadyExists == false)
                {
                    db.InsertActivity((int)comboboxNewActivityCategory.SelectedValue, textboxNewActivityName.Text);
                    LoadActivtiesList();
                    MessageBox.Show("Activity Added");
                }
                else
                {
                    MessageBox.Show("Activity already exists!");
                }
            }
        }

        private void textboxNewActivityName_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        // Record Tab

        //submit record to database
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            var d1 = datePicker1.SelectedDate;
            var d2 = datePicker6.SelectedDate;
            var h1 = comboBox1.SelectedValue;
            var m1 = comboBox2.SelectedValue;
            var t1 = comboBox3.SelectedValue;
            var h2 = comboBox4.SelectedValue;
            var m2 = comboBox5.SelectedValue;
            var t2 = comboBox6.SelectedValue;
            var c = comboBox7.SelectedValue;
            var a = comboBox9.SelectedValue;

            if (d1 == null)
            {
                MessageBox.Show("You must select a start date");
            }
            else if (d2 == null)
            {
                MessageBox.Show("You must select an end date");
            }
            else if (h1 == null || m1 == null || t1 == null)
            {
                MessageBox.Show("You must enter a start time");
            }
            else if (h2 == null || m2 == null || t2 == null)
            {
                MessageBox.Show("You must enter an end time");
            }
            else if (c == null)
            {
                MessageBox.Show("You must select a category");
            }
            else if (a == null)
            {
                MessageBox.Show("You must select an activity");
            }
            else 
            {
                DateTime sDate = (DateTime)datePicker1.SelectedDate;
                DateTime eDate = (DateTime)datePicker6.SelectedDate;
                Int32 hour1 = Convert.ToInt32(comboBox1.SelectionBoxItem.ToString());
                Int32 min1 = Convert.ToInt32(comboBox2.SelectionBoxItem.ToString());
                string aop1 = comboBox3.SelectionBoxItem.ToString();

                if (aop1.Equals("PM", StringComparison.Ordinal))
                {
                    if (hour1 != 12)
                    {
                        hour1 += 12;
                    }
                }
                else
                {
                    if (hour1 == 12)
                    {
                        hour1 = 0;
                    }
                }

                Int32 hour2 = Convert.ToInt32(comboBox4.SelectionBoxItem.ToString());
                Int32 min2 = Convert.ToInt32(comboBox5.SelectionBoxItem.ToString());
                string aop2 = comboBox6.SelectionBoxItem.ToString();

                if (aop2.Equals("PM", StringComparison.Ordinal))
                {
                    if (hour2 != 12)
                    {
                        hour2 += 12;
                    }
                }
                else
                {
                    if (hour2 == 12)
                    {
                        hour2 = 0;
                    }
                }

                TimeSpan start = new TimeSpan(hour1, min1, 0);
                TimeSpan end = new TimeSpan(hour2, min2, 0);

                DateTime sDate2 = sDate.Add(start);
                DateTime eDate2 = eDate.Add(end);

                if (eDate2.CompareTo(sDate2) < 0)
                {
                    MessageBox.Show("Your start date must be before your end date");
                }
                else
                {
                    if (sDate2.CompareTo(this.sessionStartDate) < 0
                        || eDate2.CompareTo(this.sessionEndDate) > 0)
                    {
                        MessageBox.Show("Activity Dates Do Not Fall Within The Current Sessions Time Period");
                    }
                    else
                    {
                        db.InsertSessionActivity(this.sessionID, Convert.ToInt32(comboBox7.SelectedValue), Convert.ToInt32(comboBox9.SelectedValue), sDate2, eDate2);
                        MessageBox.Show("Record Submitted Successfully");
                    }
                }
            }
        }


        private void comboBox7_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LoadActivitiesCombo();
        }

        // Report Tab

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            if (comboBox10.SelectedItem == DateToDateFullReport)
            {
                if (datePicker2.SelectedDate == null || datePicker3.SelectedDate == null)
                {
                    MessageBox.Show("One or more date selectors have been left empty or contain invalid dates.");
                    return;
                }
                
                List<SessionActivity> sa = db.GetActivitiesBetweenDatesSorted(this.sessionID, (DateTime)datePicker2.SelectedDate, (DateTime)datePicker3.SelectedDate);
                Window report = new BasicReport(sa, "Date to Date Full Report");
                report.Show();
            }
            if (comboBox10.SelectedItem == CategoryComparisonReport)
            {
                if (datePicker2.SelectedDate == null || datePicker3.SelectedDate == null)
                {
                    MessageBox.Show("One or more date selectors have been left empty or contain invalid dates.");
                    return;
                }
                List<Category> cats = db.GetCategories();
                Window report = new CategoryComparison((DateTime)datePicker2.SelectedDate, (DateTime)datePicker3.SelectedDate, this.sessionID, "Category Comparison Report", cats);
                report.Show();
            }
            if (comboBox10.SelectedItem == CategoryDetailReport)
            {
                if (datePicker2.SelectedDate == null || datePicker3.SelectedDate == null)
                {
                    MessageBox.Show("One or more date selectors have been left empty or contain invalid dates.");
                    return;
                }
                string sel = comboBox8.SelectedItem.ToString();
                List<Category> cats = db.GetCategories();
                Category cat = cats[0];
                for (int i = 0; i < cats.Count; i++)
                {
                    if (cats[i].Name == sel)
                        cat = cats[i];
                }
                List<SessionActivity> sa = db.GetActivitiesBetweenDatesByCategorySorted(this.sessionID, (DateTime)datePicker2.SelectedDate, (DateTime)datePicker3.SelectedDate, cat.CategoryID);
                Window report = new BasicReport(sa, "Category Detail Report");
                report.Show();
            }
            if (comboBox10.SelectedItem == DateToDateComparisonReport)
            {
                if (datePicker2.SelectedDate == null || datePicker3.SelectedDate == null || datePicker4.SelectedDate == null || datePicker5.SelectedDate == null)
                {
                    MessageBox.Show("One or more date selectors have been left empty or contain invalid dates.");
                    return;
                }
                List<SessionActivity> sa1 = db.GetActivitiesBetweenDatesSorted(this.sessionID, (DateTime)datePicker2.SelectedDate, (DateTime)datePicker3.SelectedDate);
                List<SessionActivity> sa2 = db.GetActivitiesBetweenDatesSorted(this.sessionID, (DateTime)datePicker4.SelectedDate, (DateTime)datePicker5.SelectedDate);
                Window report = new ComparisonReportView(sa1, sa2, "Date to Date Comparison Report");
                report.Show();
            }
            if (comboBox10.SelectedItem == CategoryBreakdownComparisonReport)
            {
                if (datePicker2.SelectedDate == null || datePicker3.SelectedDate == null || datePicker4.SelectedDate == null || datePicker5.SelectedDate == null)
                {
                    MessageBox.Show("One or more date selectors have been left empty or contain invalid dates.");
                    return;
                }
                List<Category> cats = db.GetCategories();
                Window report = new ComparisonBreakoutReport((DateTime)datePicker2.SelectedDate, (DateTime)datePicker3.SelectedDate, (DateTime)datePicker4.SelectedDate, (DateTime)datePicker5.SelectedDate, this.sessionID, "Category Comparison Report", cats);
                report.Show();
            }

            if (comboBox10.SelectedItem == CategoryDetailComparisonReport)
            {
                if (datePicker2.SelectedDate == null || datePicker3.SelectedDate == null || datePicker4.SelectedDate == null || datePicker5.SelectedDate == null)
                {
                    MessageBox.Show("One or more date selectors have been left empty or contain invalid dates.");
                    return;
                }
                string sel = comboBox8.SelectedItem.ToString();
                List<Category> cats = db.GetCategories();
                Category cat = cats[0];
                for (int i = 0; i < cats.Count; i++)
                {
                    if (cats[i].Name == sel)
                        cat = cats[i];
                }

                List<SessionActivity> sa1 = db.GetActivitiesBetweenDatesByCategorySorted(this.sessionID, (DateTime)datePicker2.SelectedDate, (DateTime)datePicker3.SelectedDate, cat.CategoryID);
                List<SessionActivity> sa2 = db.GetActivitiesBetweenDatesByCategorySorted(this.sessionID, (DateTime)datePicker4.SelectedDate, (DateTime)datePicker5.SelectedDate, cat.CategoryID);
                Window report = new ComparisonReportView(sa1, sa2, "Category Detail Comparison Report");
                report.Show();
            }
        }

        public ObservableCollection<string> CatNames
        { get { return _CatNames; } }

        private void CategoryDetailReport_Selected(object sender, RoutedEventArgs e)
        {
            List<string> temp = new List<string>();
            comboBox8.Visibility = Visibility.Visible;
            categoryLabel.Visibility = Visibility.Visible;
            List<Category> categs = db.GetCategories();
            for (int i = 0; i < categs.Count; i++)
            {
                Console.WriteLine(categs[i].Name);
                temp.Add(categs[i].Name);

            }
            temp.Sort();
            for (int i = 0; i < temp.Count; i++)
                _CatNames.Add(temp[i]);
            comboBox8.ItemsSource = CatNames;
            comboBox8.SelectedItem = CatNames[0];
        }

        private void CategoryDetailReport_Unselected(object sender, RoutedEventArgs e)
        {
            _CatNames.Clear();
        }

        private void DateToDateComparisonReport_Selected(object sender, RoutedEventArgs e)
        {

            datePicker4.Visibility = Visibility.Visible;
            datePicker5.Visibility = Visibility.Visible;
            label10.Visibility = Visibility.Visible;
            label16.Visibility = Visibility.Visible;
            label20.Visibility = Visibility.Visible;

        }
        private void DateToDateComparisonReport_Unselected(object sender, RoutedEventArgs e)
        {

            datePicker4.Visibility = Visibility.Hidden;
            datePicker5.Visibility = Visibility.Hidden;
            label10.Visibility = Visibility.Hidden;
            label16.Visibility = Visibility.Hidden;
            label20.Visibility = Visibility.Hidden;

        }

        private void CategoryDetailComparisonReport_Selected(object sender, RoutedEventArgs e)
        {

            datePicker4.Visibility = Visibility.Visible;
            datePicker5.Visibility = Visibility.Visible;
            label10.Visibility = Visibility.Visible;
            label16.Visibility = Visibility.Visible;
            label20.Visibility = Visibility.Visible;
            List<string> temp = new List<string>();

            List<Category> categs = db.GetCategories();
            for (int i = 0; i < categs.Count; i++)
            {
                Console.WriteLine(categs[i].Name);
                temp.Add(categs[i].Name);

            }
            temp.Sort();
            Console.WriteLine("REDALERT!!!");
            for (int i = 0; i < temp.Count; i++)
                _CatNames.Add(temp[i]);
            comboBox8.ItemsSource = CatNames;
            comboBox8.SelectedItem = CatNames[0];
            comboBox8.Visibility = Visibility.Visible;
            categoryLabel.Visibility = Visibility.Visible;

        }
        private void CategoryDetailComparisonReport_Unselected(object sender, RoutedEventArgs e)
        {

            datePicker4.Visibility = Visibility.Hidden;
            datePicker5.Visibility = Visibility.Hidden;
            label10.Visibility = Visibility.Hidden;
            label16.Visibility = Visibility.Hidden;
            label20.Visibility = Visibility.Hidden;
            _CatNames.Clear();

        }



        private void comboBox10_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBox10.SelectedItem == CategoryDetailReport || comboBox10.SelectedItem == CategoryDetailComparisonReport)
            {

            }
            else
            {
                try
                {
                    comboBox8.Visibility = Visibility.Hidden;
                    categoryLabel.Visibility = Visibility.Hidden;
                }
                catch
                {
                }
            }
        }

        private void buttonCreateSession_Click(object sender, RoutedEventArgs e)
        {
            bool submitSession = true;

            if (textboxFirstName.Text == "")
            {
                MessageBox.Show("You must enter a first name");
                submitSession = false;
            }

            else if (textboxLastName.Text == "")
            {
                MessageBox.Show("You must enter a last name");
                submitSession = false;
            }

            else if (datePickerEndDate.SelectedDate == null)
            {
                MessageBox.Show("You must select an end date.");
                submitSession = false;
            }

            else if (datePickerStartDate.SelectedDate == null)
            {
                MessageBox.Show("You must select a start date.");
                submitSession = false;
            }

            if (submitSession == true)
            {

                DateTime end = (DateTime)datePickerEndDate.SelectedDate;
                end = end.AddHours(1);
                end = end.AddMinutes(1);
                end = end.AddSeconds(1);
                db.InsertSession(textboxFirstName.Text, textboxLastName.Text, (DateTime)datePickerStartDate.SelectedDate, end);
                LoadSessionList();
            }

        }

        private void buttonLoadSession_Click(object sender, RoutedEventArgs e)
        {
            if (listBoxSessions.SelectedValue != null)
            {
                this.sessionID = (int)listBoxSessions.SelectedValue;

                Session ses = db.GetSessionById((int)listBoxSessions.SelectedValue);
                this.sessionStartDate = ses.StartDate;
                this.sessionEndDate = ses.EndDate;

                tabActivities.IsEnabled = true;
                tabCategories.IsEnabled = true;
                tabRecord.IsEnabled = true;
                tabReports.IsEnabled = true;

                IEnumerable<object> day = db.GetActivityRemindersDaily(this.sessionID);
                IEnumerable<object> month = db.GetActivityRemindersMonthly(this.sessionID);
                IEnumerable<object> week = db.GetActivityRemindersWeekly(this.sessionID);

                MessageBox.Show("Session Loaded");

                if (day.ToList().Count != 0 || week.ToList().Count != 0 || month.ToList().Count != 0)
                {
                    Window predict = new Predictions(this.sessionID);
                    predict.Show();
                }
            }
            else
            {
                MessageBox.Show("You must select a session!");
            }
        }
    }
}
